package cn.lili.controller.feign.trade;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.modules.order.order.entity.dos.Trade;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.service.TradeService;
import cn.lili.modules.order.payment.TradeCashier;
import cn.lili.modules.order.trade.client.TradeClient;
import cn.lili.modules.payment.entity.dto.PaymentCallback;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.OrderSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 交易 feign clietn
 *
 * @author Chopper
 * @version v1.0
 * 2021-12-07 19:04
 */
@RestController
@RequiredArgsConstructor
public class TradeFeignController implements TradeClient {

    private final TradeService tradeService;

    private final TradeCashier tradeCashier;

    private final SettingClient settingClient;

    @Override
    public Trade getBySn(String sn) {
        return tradeService.getBySn(sn);
    }

    @Override
    public void paymentCallback(PaymentCallback paymentCallback) {
        System.out.println("支付回调订单处理 回调来了============");
        tradeCashier.paymentCallback(paymentCallback);
    }

    @Override
    public void paymentCallbackZero(String sn) {
        tradeService.paymentCallbackZero(sn);
    }

    @Override
    public void scheduledCancel() {
        Setting setting = settingClient.get(SettingEnum.ORDER_SETTING.name());
        OrderSetting orderSetting = JSONUtil.toBean(setting.getSettingValue(), OrderSetting.class);
        if (orderSetting != null && orderSetting.getAutoCancel() != null) {
            //订单自动取消时间 = 当前时间 - 自动取消时间分钟数
            DateTime cancelTime = DateUtil.offsetMinute(DateUtil.date(), -orderSetting.getAutoCancel());
            LambdaQueryWrapper<Trade> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Trade::getOrderStatus, OrderStatusEnum.UNPAID.name());
            queryWrapper.le(Trade::getCreateTime, cancelTime);
            List<Trade> tradeList = tradeService.list(queryWrapper);


            for (Trade trade : tradeList) {
                tradeService.systemCancel(trade.getSn(), "超时未支付自动取消");
            }
        }
    }
}
